package com.threegroup.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.threegroup.admin.dao.SysUserDao;
import com.threegroup.admin.dto.PasswordDTO;
import com.threegroup.admin.dto.SysUserDTO;
import com.threegroup.admin.entity.SysUserEntity;
import com.threegroup.admin.enums.SuperAdminEnum;
import com.threegroup.admin.exceptions.ParamsException;
import com.threegroup.admin.query.SysUserQuery;
import com.threegroup.admin.security.user.SecurityUser;
import com.threegroup.admin.service.ISysDeptService;
import com.threegroup.admin.service.ISysRoleUserService;
import com.threegroup.admin.service.ISysUserService;
import com.threegroup.common.exception.ErrorCode;
import com.threegroup.common.utils.BeanCopierUtils;
import com.threegroup.common.utils.Result;
import com.threegroup.common.validator.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 系统用户服务接口实现类
 */
@Service
public class SysUserServiceImpl implements ISysUserService {

    @Resource
    private SysUserDao sysUserDao;

    @Resource
    private ISysDeptService sysDeptService;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private ISysRoleUserService sysRoleUserService;

    /**
     * 分页获取用户列表
     * @param sysUserQuery 查询条件
     * @return
     */
    @Override
    public Result<Map<String, Object>> getUserList(SysUserQuery sysUserQuery) {

        PageHelper.startPage(sysUserQuery.getPage(), sysUserQuery.getLimit());

        //普通管理员，只能查询所属部门及子部门的数据
        SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (sysUserQuery.getDeptId() != null) {
            if (securityUser.getSuperAdmin() == SuperAdminEnum.NO.value()) {
                sysUserQuery.setDeptList(sysDeptService.getSubDeptIdList(securityUser.getDeptId()));
            } else {
                sysUserQuery.setDeptList(Collections.singletonList(sysUserQuery.getDeptId()));
            }
        }

        List<SysUserEntity> sysUserEntityList = sysUserDao.selectUserList(sysUserQuery);

        PageInfo<SysUserEntity> pageInfo = new PageInfo<SysUserEntity>(sysUserEntityList);

        Map<String, Object> map = new HashMap<>();
        map.put("list", pageInfo.getList());
        map.put("total",(int) pageInfo.getTotal());

        return new Result<Map<String, Object>>().ok(map);
    }

    /**
     * 保存用户信息
     * @param sysUserDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysUserDTO sysUserDTO) {

        SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        SysUserEntity sysUserEntity = BeanCopierUtils.copy(sysUserDTO, SysUserEntity.class);
        // 密码加密
        sysUserEntity.setPassword(passwordEncoder.encode(sysUserDTO.getPassword()));

        // 保存用户
        sysUserEntity.setSuperAdmin(SuperAdminEnum.NO.value());
        sysUserEntity.setCreateDate(new Date());
        sysUserEntity.setUpdateDate(new Date());
        sysUserEntity.setCreator(securityUser.getUid());
        sysUserEntity.setUpdater(securityUser.getUid());

        int count = sysUserDao.save(sysUserEntity);

        // 保存用户角色关系
       sysRoleUserService.saveOrUpdate(sysUserEntity.getId(), sysUserDTO.getRoleIdList());

    }

    /**
     * 根据用户id 获取用户信息
     * @param uid 用户id
     * @return
     */
    @Override
    public SysUserDTO getUserInfoById(Long uid) {

        if (uid == null) {
            throw  new ParamsException("用户uid不存在!");
        }

        SysUserEntity sysUserEntity = sysUserDao.selectUserById(uid);
        SysUserDTO sysUserDTO = BeanCopierUtils.copy(sysUserEntity, SysUserDTO.class);

        List<Long> roleIdList = sysRoleUserService.getRoleIdList(uid);
        sysUserDTO.setRoleIdList(roleIdList);

        return sysUserDTO;
    }

    /**
     * 修改用户信息
     * @param sysUserDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUserDTO sysUserDTO) {

        SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        SysUserEntity sysUserEntity = BeanCopierUtils.copy(sysUserDTO, SysUserEntity.class);
        if (StringUtils.isNotBlank(sysUserDTO.getPassword())) {
            // 密码加密
            sysUserEntity.setPassword(passwordEncoder.encode(sysUserDTO.getPassword()));
        } else {
            sysUserEntity.setPassword(null);
        }

        // 保存用户
        sysUserEntity.setUpdateDate(new Date());
        sysUserEntity.setUpdater(securityUser.getUid());

        int count = sysUserDao.update(sysUserEntity);

        // 保存用户角色关系
        sysRoleUserService.saveOrUpdate(sysUserEntity.getId(), sysUserDTO.getRoleIdList());

    }

    /**
     * 删除用户信息
      * @param ids 主键id列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long[] ids) {

        //删除用户
        int count = sysUserDao.deleteBatchIds(ids);

        //删除角色用户关系
        sysRoleUserService.deleteByUserIds(ids);

        return count;
    }

    /**
     * 获取用户数据
     * @param sysUserQuery
     * @return
     */
    @Override
    public List<SysUserDTO> list(SysUserQuery sysUserQuery) {
        //普通管理员，只能查询所属部门及子部门的数据
        SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (sysUserQuery.getDeptId() != null) {
            if (securityUser.getSuperAdmin() == SuperAdminEnum.NO.value()) {
                sysUserQuery.setDeptList(sysDeptService.getSubDeptIdList(securityUser.getDeptId()));
            } else {
                sysUserQuery.setDeptList(Collections.singletonList(sysUserQuery.getDeptId()));
            }
        }

        List<SysUserEntity> entityList = sysUserDao.selectUserList(sysUserQuery);

        return BeanCopierUtils.copyList(entityList, SysUserDTO.class);
    }

    /**
     * 密码修改
     *
     * @param passwordDTO
     * @return
     */
    @Override
    public Result<String> doEditPassword(PasswordDTO passwordDTO) {
        // 参数校验
        ValidatorUtils.validateEntity(passwordDTO);

        SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //原密码不正确
        if(!passwordEncoder.matches(passwordDTO.getPassword(), securityUser.getPassword())){
            return new Result<String>().error(ErrorCode.PASSWORD_ERROR);
        }

        // 更新密码
        int count = sysUserDao.updatePassword(securityUser.getUid(), passwordEncoder.encode(passwordDTO.getNewPassword()));

        if (count < 0) {
            return new Result<String>().error(ErrorCode.UPDATE_PASSWORD_ERROR);
        }

        return new Result<>();
    }
}
